﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DotSpatial.Controls;
using GeostatisticalTool.Classes;
using DotSpatial.Data;
using System.IO;
using DotSpatial.Projections;
using DotSpatial.Topology;
using DotSpatial.Symbology;

namespace GeostatisticalTool.Forms
{
    public partial class Interpolators : System.Windows.Forms.Form
    {
        private Map map;
        public ConfigurationMethod env{set;get;}
        public bool OutputParameters { set; get; }
       
        SemivarianceCovarianceGraph semiGraph;
        SpatialContinuity spatial;
        AnisotropyValues anisotropy;
        TheoreticalModel theoretical;
        IInterpolator _trend;
        IKriging dataK;
        TheoreticalModelAnisotropy theoreticalAniso;
        CrossValidationCheck crossValidation;
        Extent ext;
        //
        bool filterByField = false;




        //

        public Interpolators()
        {
            this.map = null;
            InitializeComponent();
        }

        public Interpolators(Map map)
        {
            this.map = map;
            InitializeComponent();
        }

        public Interpolators(Map map, bool filterByField)
        {
            this.map = map;
            this.filterByField = filterByField;
            InitializeComponent();
        }


        public double[] GetTheoreticalModelParameters()
        {
            if (theoretical == null)
                return null;
            else
            {

                double v=1;
                if (theoreticalModelControl1.KrigingModel.Name == "Circular")
                    v = 0;
                if (theoreticalModelControl1.KrigingModel.Name == "Exponential")
                    v = 1;
                if (theoreticalModelControl1.KrigingModel.Name == "Gaussian")
                    v = 2;
                if (theoreticalModelControl1.KrigingModel.Name == "Spherical")
                    v = 3;
                return new double[]{ v,
                    Convert.ToDouble(theoreticalModelControl1.MajorRange),
                     Convert.ToDouble(theoreticalModelControl1.Sill),
                     Convert.ToDouble(theoreticalModelControl1.Nugget),
                     0,
                      0,
                      env.MeanValue
                };
            }
        }




        private void Interpolators_Load(object sender, EventArgs e)
        {
           
            uxTypeOfMethod2.SelectedIndex = 0;
            uxTypeOfOutput2.SelectedIndex = 0; 
            uxTransformation.SelectedIndex = 0;
            uxRemoveTrend.SelectedIndex = 0;
            zedGraphControl1.BorderStyle = BorderStyle.None;
            zedGraphControl2.BorderStyle = BorderStyle.None;

            uxNextPrevious.SetTab(uxPages);
            if (env == null)
            {
                env = new ConfigurationMethod(
                this.map,
                uxTypeOfMethod2,
                uxTypeOfOutput2,
                uxLayer,
                uxField,
                uxTransformation,
                uxRemoveTrend, this.filterByField);
                env.uxCheck = uxCheck;
            }
            else
            {
              uxDataset.Visible = false;
              env.SetParameters(this.map,
                    uxTypeOfMethod2,
                    uxTypeOfOutput2,
                    uxLayer,
                    uxField,
                    uxTransformation,
                    uxRemoveTrend, 
                    this.filterByField);
            
            }

            uxNextPrevious.SelectedNext +=new EventHandler(uxNextPrevious_SelectedNext);
            uxNextPrevious.SelectedPrevious +=new EventHandler(uxNextPrevious_SelectedPrevious);
            uxNextPrevious.uxClose.Click += new EventHandler(uxClose_Click);

        }


        private void uxNextPrevious_SelectedNext(object sender, EventArgs e)
        {

            if (uxPages.SelectedIndex == 0)
            {
                SelectorMethodProcedure();
                return;
            }
            if (uxPages.SelectedIndex == 1)
            {

                uxPages.TabPages[0].Enabled = false;
                uxPages.TabPages[1].Enabled = false;
                uxPages.TabPages[2].Enabled = true;
                uxPages.SelectedIndex = 2;
                StartKriging();
                return;
            }
            if (uxPages.SelectedIndex == 2)
            {
                CreateSearchNeighborhodAnalysis();
                return;
            }

            if (uxPages.SelectedIndex == 3)
            {
                CreateCrossValidation();
                return;
            }

        }

        private void uxNextPrevious_SelectedPrevious(object sender, EventArgs e)
        {
            if (uxPages.SelectedIndex == 1)
            {
                uxPages.TabPages[2].Enabled = false;
                uxPages.TabPages[1].Enabled = false;
                uxPages.TabPages[0].Enabled = true;
                uxPages.SelectedIndex = 0;

                uxPredictedValue2.ChangedCoordinate -= uxPredictedValue2_ChangedCoordinate;
                uxMapTrend.ChangedCoordinate -= uxMapTrend_ChangedCoordinate;

                return;
            
            }
            if (uxPages.SelectedIndex == 2)
            {
                if (env.Trend != 0)
                {
                    uxPages.TabPages[2].Enabled = false;
                    uxPages.TabPages[1].Enabled = true;
                    uxPages.SelectedIndex = 1;
                }
                else
                {
                    uxPages.TabPages[2].Enabled = false;
                    uxPages.TabPages[1].Enabled = false;
                    uxPages.TabPages[0].Enabled = true;
                    uxPages.SelectedIndex = 0;

                }
                return;
            
            }
            if (uxPages.SelectedIndex == 3)
            {
                uxPages.TabPages[2].Enabled = true;
                uxPages.TabPages[3].Enabled = false;
                uxPages.SelectedIndex = 2;
                uxSearchNeighborhoodControl1.ChangedParameters -= uxSearchNeighborhoodControl1_ChangedParameters;
                uxPredictedValue1.ChangedCoordinate -= uxPredictedValue1_ChangedCoordinate;
                uxKrigingInterpo.ChangedCoordinate -= uxKrigingInterpo_ChangedCoordinate;
                return;
            }

            if (uxPages.SelectedIndex == 4)
            {
                uxPages.TabPages[3].Enabled = true;
                uxPages.TabPages[4].Enabled = false;
                uxPages.SelectedIndex = 3;
                return;
            }


        }

        private void SelectorMethodProcedure()
        {
            uxMapTrend.SetProjection(env.OriginalData.Projection);
            uxContinuity.SetProjection(KnownCoordinateSystems.Projected.UtmWgs1984.WGS1984UTMZone10N);
            uxKrigingInterpo.SetProjection(env.OriginalData.Projection);

            if (env.Field != null)
            {
                bool continueI=false;
                if (uxFilter.Visible && !String.IsNullOrEmpty(uxFilter.Text))
                    continueI = env.Load(uxFilter.Text);
                else
                    continueI = env.Load();

                if (continueI)
                {
                    if (uxFilter.Visible && !String.IsNullOrEmpty(uxOutputSelection.Text))
                        try
                        {
                            env.Data.SaveAs(uxOutputSelection.Text, true);
                        }
                        catch
                        {
                            MessageBox.Show("The selection data was not saved");
                        }

                    if (env.Transformation != "None" && env.Trend != 0)
                    {


                        //Measured,Trans,Trend, predictedValue1,Error,stdError,stdezError,norValue
                        Trend t = new Trend(env.Data, 1, env.Trend - 1, env.MeanValue);
                        _trend = t;
                        double cell = env.Data.Extent.Width / 50;
                        uxMapTrend.ValuesMinMax = t.extentZ;
                        IRaster newgrid = t.Surface(env.Data.Extent, cell, env.Data.Projection, -32768, Path.GetTempPath() + "\\t.bgd");////********************change path
                        //  newgrid.Name = "Trend";
                        uxMapTrend.SetSurface(newgrid);

                        uxGoodOfFit.Text = Convert.ToString(t.CrossValidation()[0]);

                        uxOrderOfPolynomial.Text = uxRemoveTrend.Text;

                        env.RemoveTrend(1, t);


                        uxPredictedValue2.ChangedCoordinate += uxPredictedValue2_ChangedCoordinate;
                        uxMapTrend.ChangedCoordinate += uxMapTrend_ChangedCoordinate;



                        uxPages.TabPages[1].Enabled = true;
                        uxPages.SelectedIndex = 1;

                    }

                    if (env.Transformation == "None" && env.Trend != 0)
                    {
                        //Measured,Trans,Trend, predictedValue1,Error,stdError,stdezError,norValue

                        Trend t = new Trend(env.Data, 0, env.Trend - 1, env.MeanValue);
                        _trend = t;
                        double cell = env.Data.Extent.Width / 50;
                        uxMapTrend.ValuesMinMax = t.extentZ;
                        IRaster newgrid = t.Surface(env.Data.Extent, cell, env.Data.Projection, -32768, Path.GetTempPath() + "\\t.bgd");////********************change path
                        //  newgrid.Name = "Trend";
                        uxMapTrend.SetSurface(newgrid);

                        uxGoodOfFit.Text = Convert.ToString(t.CrossValidation()[0]);

                        uxOrderOfPolynomial.Text = uxRemoveTrend.Text;

                        env.RemoveTrend(0, t);

                        uxPredictedValue2.ChangedCoordinate += uxPredictedValue2_ChangedCoordinate;
                        uxMapTrend.ChangedCoordinate += uxMapTrend_ChangedCoordinate;

                        uxPages.TabPages[1].Enabled = true;
                        uxPages.SelectedIndex = 1;

                    }

                    if (env.Transformation == "None" && env.Trend == 0)
                    {
                        uxPages.TabPages[1].Enabled = false;
                        uxPages.TabPages[2].Enabled = true;
                        uxPages.SelectedIndex = 2;
                        env.UpdateWorkField(0);
                        StartKriging();

                    }

                    if (env.Transformation != "None" && env.Trend == 0)
                    {
                        uxPages.TabPages[1].Enabled = false;
                        uxPages.TabPages[2].Enabled = true;
                        uxPages.SelectedIndex = 2;
                        env.UpdateWorkField(1);
                        StartKriging();

                    }

                }
            }
            uxOutputInterpolation.DataSource = env.Data.DataTable;
        }

        private void StartKriging()
        {
            //8--> used field

             if (env.Method== "Ordinary Kriging")
             dataK = new Kriging(env.Data, 6);
            
             if (env.Method == "Simple Kriging")
                 dataK = new SimpleKriging(env.Data, 6);
           
            if (env.Method == "Universal Kriging")
                 dataK = new UniversalKriging(env.Data, 6);
             

             spatial = new SpatialContinuity(dataK.GetDataSource());

             anisotropy = new AnisotropyValues(spatial);

             anisotropyControl1.SetAnisotropy(anisotropy);

             

             spatial.ChangedLagParameter +=new EventHandler(Spatial_ChangedLagParameter);
             anisotropy.ChangedAnisotropyParameter += new EventHandler(Spatial_ChangedAnisotropyParameter);


             uxContinuity.ValuesMinMax = new double[2] { 0, spatial.SemivarianceStatistic.Max };

            uxLag.Spatial = spatial;
            uxLag.NumberOfLags = spatial.NumberOfLags.ToString();
            uxLag.LagSize = spatial.LagSize.ToString();
            uxLag.Tolerance = spatial.LagValue.tolerance.ToString();
            uxLag.EnableUpdateLag();
            
            uxContinuity.SetSurface(spatial.Surface(Path.GetTempPath()+"\\t2.bgd"));
           
            semiGraph = new SemivarianceCovarianceGraph(zedGraphControl1, spatial);
            semiGraph.Graph();
            theoretical = new TheoreticalModel(spatial);
            IKrigingModel model = theoretical.GetFunctionDefault();

            
            semiGraph.DrawCurve(theoretical.GetFunctionDefault());
            
            theoreticalModelControl1.TheoreticalModel = theoretical;
            uxContinuity.SetLayer(spatial.InfluenceZone(theoretical.KrigingModel.Range, theoretical.KrigingModel.Range,0));
            theoretical.ChangedKriginParameter +=new EventHandler(theoretical_ChangedKriginParameter);
            theoreticalModelControl1.ChangedAnisotropyParameter += new EventHandler(theoreticalModelControl1_ChangedAnisotropyParameter);


        
        }

        private void theoreticalModelControl1_ChangedAnisotropyParameter(object sender, EventArgs e)
        {
            if (theoreticalModelControl1.Anysotropy)
            {
            theoreticalAniso = new TheoreticalModelAnisotropy((TheoreticalModel)theoretical.Clone(), (AnisotropyValues)anisotropy.Clone());
            theoreticalModelControl1.MajorRange = theoreticalAniso.GetMajorRange().ToString();
            theoreticalModelControl1.MinorRange = theoreticalAniso.GetMinorRange().ToString();
            theoreticalModelControl1.Azimuth = theoreticalAniso.GetAzimuth().ToString();
            }
        
        }

        private void Spatial_ChangedAnisotropyParameter(object sender, EventArgs e)
        {
           // semiGraph
            semiGraph.Spatial = anisotropy;
            semiGraph.Graph();
            uxContinuity.SetLayer(anisotropy.ZoneSearch());
            semiGraph.DrawCurve(theoreticalModelControl1.TheoreticalModel.KrigingModel);
  
        }

        private void theoretical_ChangedKriginParameter(object sender, EventArgs e)
        {
            semiGraph.DrawCurve(theoreticalModelControl1.TheoreticalModel.KrigingModel);
        }

        private void Spatial_ChangedLagParameter(object sender, EventArgs e)
        {  
           // spatial= (SpatialContinuity)sender;
            uxContinuity.ValuesMinMax = new double[2] { 0, spatial.SemivarianceStatistic.Max };
            uxContinuity.SetSurface(spatial.Surface(Path.GetTempPath() +"\\t2.bgd"));
         
            semiGraph.Spatial = spatial;
            semiGraph.Graph();
            theoretical.Spatial = spatial;
            IKrigingModel model = theoretical.GetFunctionDefault();
            semiGraph.DrawCurve(theoretical.GetFunctionDefault());
            theoreticalModelControl1.TheoreticalModel = theoretical;
            uxContinuity.SetLayer(spatial.InfluenceZone(theoreticalModelControl1.MajorRange,theoreticalModelControl1.MinorRange,theoreticalModelControl1.Azimuth));

        }

        private void uxShowSearchDirection_CheckedChanged(object sender, EventArgs e)
        {
            anisotropyControl1.Visible = uxShowSearchDirection.Checked;
            if (uxShowSearchDirection.Checked)
            {
                semiGraph.Spatial = anisotropy;
                uxContinuity.SetLayer(anisotropy.ZoneSearch());
                theoretical.Spatial = anisotropy;
            }
            else
            {
                semiGraph.Spatial = spatial;
                theoretical.Spatial = spatial;
                uxContinuity.SetLayer(spatial.InfluenceZone(theoreticalModelControl1.MajorRange, theoreticalModelControl1.MinorRange, theoreticalModelControl1.Azimuth));

            }

            semiGraph.Graph();
            

        }

        private void theoreticalModelControl1_Load(object sender, EventArgs e)
        {

        }

        private void CreateSearchNeighborhodAnalysis()
        {
            uxPages.TabPages[2].Enabled = false;
            uxPages.TabPages[3].Enabled = true;
            uxPages.SelectedIndex = 3;


            uxSearchNeighborhoodControl1.MajorR = Convert.ToDouble(theoreticalModelControl1.MajorRange);
            if (theoreticalModelControl1.MinorRange != "")
            {
                uxSearchNeighborhoodControl1.MinorR = Convert.ToDouble(theoreticalModelControl1.MinorRange);
            }
            else
            {
                uxSearchNeighborhoodControl1.MinorR = Convert.ToDouble(theoreticalModelControl1.MajorRange);
            }

            uxSearchNeighborhoodControl1.Type = 1;

            if (theoreticalModelControl1.Azimuth != "")
                uxSearchNeighborhoodControl1.Az = Convert.ToDouble(theoreticalModelControl1.Azimuth);
            else
            {
                uxSearchNeighborhoodControl1.Az = 0;
            }

            dataK.GetSearch().SetAniso(uxSearchNeighborhoodControl1.Az, uxSearchNeighborhoodControl1.MinorR, uxSearchNeighborhoodControl1.MajorR);

            uxSearchNeighborhoodControl1.SetSearch(dataK.GetSearch());

            uxSearchNeighborhoodControl1.ChangedParameters += new EventHandler(uxSearchNeighborhoodControl1_ChangedParameters);
            uxSearchNeighborhoodControl1.EnableApply(false);

            uxPredictedValue1.ChangedCoordinate += new EventHandler(uxPredictedValue1_ChangedCoordinate);
            uxKrigingInterpo.ChangedCoordinate += new EventHandler(uxKrigingInterpo_ChangedCoordinate);

            InterpolatePrevious();
        }

        private void uxSearchNeighborhoodControl1_ChangedParameters(object sender, EventArgs e)
        {
            uxPredictedValue1.Recalculate();
            RecalculatePoint();
            InsertKriginSurfaceInMap();
        }

        private void RecalculatePoint()
        {
            List<IGeometry> data = new List<IGeometry>();
            SearchData search = dataK.GetSearch();
            foreach (Kpoint p in search.SelectedPoints)
                data.Add(new DotSpatial.Topology.Point(p.X, p.Y, p.Z));

            uxKrigingInterpo.AddGeometries("point", data);
            if (uxSearchNeighborhoodControl1.Type==1)
            uxKrigingInterpo.AddGeometries("polygon",search.ZoneSelected(env.Data, uxPredictedValue1.X, uxPredictedValue1.Y, uxPredictedValue1.Z)[0]);

            if (uxSearchNeighborhoodControl1.Type == 4)
            {
                uxKrigingInterpo.AddGeometries("polygon", search.ZoneSelected(env.Data, uxPredictedValue1.X, uxPredictedValue1.Y, uxPredictedValue1.Z)[0]);
                uxKrigingInterpo.AddGeometries("line", search.ZoneSelected(env.Data, uxPredictedValue1.X, uxPredictedValue1.Y, uxPredictedValue1.Z)[1]);
            }

            uxKrigingInterpo.SetCoordinates(uxPredictedValue1.X, uxPredictedValue1.Y);
        }

        private void uxKrigingInterpo_ChangedCoordinate(object sender, EventArgs e)
        {
            uxPredictedValue1.SetCoor(dataK, uxKrigingInterpo.X, uxKrigingInterpo.Y, uxKrigingInterpo.Z);


        }

        private void uxPredictedValue1_ChangedCoordinate(object sender, EventArgs e)
        {
            RecalculatePoint();
        }

        private void uxPredictedValue2_ChangedCoordinate(object sender, EventArgs e)
        {
            uxMapTrend.SetCoordinates(uxPredictedValue2.X, uxPredictedValue2.Y);
        }

        private void uxMapTrend_ChangedCoordinate(object sender, EventArgs e)
        {
            uxPredictedValue2.SetCoor(_trend, uxMapTrend.X, uxMapTrend.Y, uxMapTrend.Z);


        }

        private void InterpolatePrevious()
        {

            InsertKriginSurfaceInMap();

            uxKrigingInterpo.SetPointLayer(env.Data);
            uxPredictedValue1.SetCoor(dataK, (env.Data.Extent.MinX + env.Data.Extent.Width / 2), (env.Data.Extent.MinY + env.Data.Extent.Height / 2), 0);
            uxPredictedValue1.EnableApply(false);
            // dataK.Search.MaxNumPoints = uxSearchNeighborhoodControl1.GetMaximumPoint();

           // env.UpdatePredicted(dataK);
            
        }

        private void InsertKriginSurfaceInMap()
        {
            dataK.SetKrigingModel(theoretical.KrigingModel);
            double cell = env.Data.Extent.Width / 30;
            uxKrigingInterpo.ValuesMinMax = dataK.GetMaxValuesZ();

            IRaster newgrid = dataK.Surface(env.Data.Extent, cell, env.Data.Projection, -32768, Path.GetTempPath() + "\\krig.bgd");////********************change path
            uxKrigingInterpo.SetSurface(newgrid);



        }

        private void CreateCrossValidation()
        {
            double[] result = dataK.CrossValidation();

            uxOutputRaster1.Map = this.map;
            uxOutputRaster1.Ext = env.Data.Extent;
            uxOutputRaster1.NameLayer = env.Layer;
            uxOutputRaster1.Name = "Kriging";
            uxOutputRaster1.Path = Path.GetTempPath();
            uxOutputRaster1.Pixel = Convert.ToString(env.Data.Extent.Width / 50);
           // uxPathFile.Text = Path.GetTempPath();
           // uxPixelSize.Text = Convert.ToString(env.Data.Extent.Width / 50);
            uxOutputRaster1.uxCreate.Click +=new EventHandler(uxCreate_Click);


            //result[0] = Math.Sqrt(SSerror / numberUsed); //RMS
            //result[1] = sumError / numberUsed; //Mean Prediction errors
            //result[2] = Math.Sqrt(averageError / numberUsed); //average krigin std error
            //result[3] = meanStdPredError / numberUsed; // Meand sdt prediction error
            //result[4] = Math.Sqrt(quadMeanStdPredError / numberUsed); //RMS sdt prediction error
            uxErrorResult.Text = string.Format(
@"   Statistical Error

            Mean prediction errors           :{1}
            RMS prediction errors              :{0}
            Average kriging standar error      :{2}
            Mean standardized prediction errors:{3}
            RMS standardized prediction errors :{4}
            ", result[0], result[1], result[2], result[3], result[4]);


            //ListOFValues  ->  true value, predicted value, error, std error /////////////////
            //"Measured","Trans","Trend","Predicted","Error","StdError"       /////////////////
            UpdataCrossValidationRegression("Measured", "Predicted", "Cross Validation", 0, 1);



            uxPages.TabPages[3].Enabled = false;
            uxPages.TabPages[4].Enabled = true;
            uxPages.SelectedIndex = 4;
            if (this.filterByField)
                uxOutputRaster1.ConfigureOutput();

        }

        private void UpdataCrossValidationRegression(string fieldX, string fieldY, string title, int indexListOfValuesX, int indexListOfValuesY)
        {

            //ListOFValues  ->  true value, predicted value, error, std error /////////////////
            //"Measured","Trans","Trend","Predicted","Error","StdError"       /////////////////
          CalculateErrorsCrossValidation cal = new CalculateErrorsCrossValidation(env.Data, env.CheckData);
          List<double[]> listOfValues=cal.UpdatePredictedTable(dataK, env.Trend, env.Transformation);
            double[]  regression= cal.CrossValidationRegression(fieldX,fieldY);
            double MaxZValue =dataK.GetMaxValuesZ()[1];
            crossValidation= new CrossValidationCheck(zedGraphControl2, listOfValues);
            uxRegression.Text = string.Format(
                fieldX + @" = {1} + {0}*" + fieldY + " r= {2}", Math.Round(regression[0], 3), Math.Round(regression[1], 3), Math.Round(regression[2], 3));

           crossValidation.DrawPoints(fieldX, fieldY,title,indexListOfValuesX, indexListOfValuesY);
           if (title == "Cross Validation")
           crossValidation.GuideLine(MaxZValue);

           crossValidation.RegressionLine(MaxZValue, regression[0], regression[1]);
        }

        private void uxClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }



        private void AssociateToGrid()
        {

            IFeatureSet fT = null;
            IMapPolygonLayer tem = null;
            foreach (IMapPolygonLayer ila in this.map.GetPolygonLayers())
            {
                fT = (IFeatureSet)ila.DataSet;
                tem = ila;
                if (ila.LegendText == "Grid")
                    break;
            }
            if (fT == null)
                return;
            Stat stat = new Stat(false);
            foreach (IFeature fea in fT.Features)
            {
                IFeature center = fea.Centroid();
                double st =dataK.Interpolate(center.Coordinates[0].X, center.Coordinates[0].Y,center.Coordinates[0].Z, true)[0];
                fea.DataRow["Field"] = st;
                stat += new Stat(st);
            }
            fT.Save();

            tem.DataSet.FillAttributes();
            PolygonScheme polScheme = new PolygonScheme();
            polScheme.EditorSettings.FieldName = "Field";
            polScheme.EditorSettings.ClassificationType = ClassificationType.Custom;

           // polScheme.EditorSettings.StartColor = Color.Green;
           // polScheme.EditorSettings.EndColor = Color.Magenta;
           //// polScheme.EditorSettings.UseColorRange = true;

           // polScheme.EditorSettings.RampColors = true;
            for (int i = 0; i < 12; i++)
            {
                PolygonCategory cat = new PolygonCategory();
                cat.SetColor(Color.FromArgb(i * 20, 50, 250 - (i * 20)));
                
                cat.Range = new Range(stat.Min + (i - 1) * (stat.Max - stat.Min) / 10, stat.Min + (i) * (stat.Max - stat.Min) / 10);
                cat.FilterExpression = string.Format("[Field]>{0} AND [Field]<={1}", Math.Round((double)cat.Range.Minimum, 3), Math.Round((double)cat.Range.Maximum, 3));
                cat.LegendText = string.Format("{0} - {1}", Math.Round((double)cat.Range.Minimum, 3), Math.Round((double)cat.Range.Maximum, 3));
                polScheme.AddCategory(cat);
            }
           
            tem.Symbology = polScheme;
          //  tem.ApplyScheme(polScheme);
            map.ResetBuffer();
        }

        private void uxCreate_Click(object sender, EventArgs e)
        {
            if (OutputParameters)
            {


            }


            if (this.filterByField)
            {
                AssociateToGrid();
                return;
            }

                this.ext = uxOutputRaster1.Ext;

                Clip clip = uxOutputRaster1.Clip;
                IRaster mask=null;


            if (Validator.IsDouble(uxOutputRaster1.Pixel) && uxOutputRaster1.Path != "")
            {
                 double pixel=Convert.ToDouble(uxOutputRaster1.Pixel);

               if (clip != null)
                {
                    mask = clip.GetClip(this.ext, pixel, @uxOutputRaster1.Path + "mask.bgd");
                }


                foreach (int i in uxTypeOfOutput2.SelectedIndices)
                {
                    if (uxTypeOfOutput2.SelectedIndices[i] == 0)
                    {
                        if (mask == null)
                        {
                            IRaster newgrid = dataK.Surface(this.ext, pixel, env.Data.Projection, -32768, @uxOutputRaster1.Path + uxOutputRaster1.NameOutput + ".bgd");////********************change path.bgd
                            map.Layers.Add(newgrid);
                        }
                        else
                        {
                            IRaster newgrid = dataK.Surface(mask,this.ext, pixel, env.Data.Projection, -32768, @uxOutputRaster1.Path + uxOutputRaster1.NameOutput + ".bgd");////********************change path.bgd
                            map.Layers.Add(newgrid);
                        }

                    

                    }

                    if (uxTypeOfOutput2.SelectedIndices[i] == 1)
                    {
                        if (mask == null)
                        {
                            IRaster newgrid = dataK.SurfaceError(this.ext, pixel, env.Data.Projection, -32768, @uxOutputRaster1.Path + uxOutputRaster1.NameOutput + "_error.bgd");////********************change path
                            map.Layers.Add(newgrid);
                        }
                        else
                        {
                            IRaster newgrid = dataK.SurfaceError(mask,this.ext, pixel, env.Data.Projection, -32768, @uxOutputRaster1.Path + uxOutputRaster1.NameOutput + "_error.bgd");////********************change path
                            map.Layers.Add(newgrid);
                        }

                    }
                }

            }

        }

        private void uxPredicted_CheckedChanged(object sender, EventArgs e)
        {
            //ListOFValues  ->  true value, predicted value, error, std error /////////////////
            //"Measured","Trans","Trend","Predicted","Error","StdError"       /////////////////
            if (uxPredicted.Checked)
            UpdataCrossValidationRegression("Measured", "Predicted", "Cross Validation", 0, 1);
        }

        private void uxError_CheckedChanged(object sender, EventArgs e)
        {
            //ListOFValues  ->  true value, predicted value, error, std error /////////////////
            //"Measured","Trans","Trend","Predicted","Error","StdError"       /////////////////
            if (uxError.Checked)
            UpdataCrossValidationRegression("Measured", "Error", "Error", 0, 2);
        }

        private void uxStdError_CheckedChanged(object sender, EventArgs e)
        {
            //ListOFValues  ->  true value, predicted value, error, std error /////////////////
            //"Measured","Trans","Trend","Predicted","Error","StdError"       /////////////////
            if (uxStdError.Checked)
            UpdataCrossValidationRegression("Measured", "StdError", "Standard Error", 0, 3);
        }

        private void uxApplyFilter_CheckedChanged(object sender, EventArgs e)
        {
            if (uxApplyFilter.Checked)
            {
                uxFilter.Visible = true;
                uxLabelFilter.Visible = true;
                uxLabelOuput.Visible = true;
                uxOutputSelection.Visible = true;

            }
            else
            {
                uxFilter.Visible = false;
                uxLabelFilter.Visible = false;
                uxLabelOuput.Visible = false;
                uxOutputSelection.Visible = false;
            }
        }

 


    }
}
